<template>
	<view class="content">
		<view class="form-box">
			<view class="title">核销信息</view>
			<view class="row-input">
				<input type="text" placeholder="客户手机号" maxlength="11" v-model="phoneNumber"
					@focus="onFocusInput('phoneNumber')" @blur="onBlurInput('phoneNumber')" />
			</view>
			<view class="row-input">
				<input type="text" placeholder="权益卡号" maxlength="20" v-model="issuedBenefitsCardNo"
					@focus="onFocusInput('issuedBenefitsCardNo')" @blur="onBlurInput('issuedBenefitsCardNo')" />
			</view>
			<view class="row-input">
				<input type="text" placeholder="产品ID" maxlength="20" v-model="productId"
					@focus="onFocusInput('productId')" @blur="onBlurInput('productId')" />
			</view>
			<view class="row-input">
				<input type="text" placeholder="核销码" maxlength="20" v-model="consumeCode"
					@focus="onFocusInput('consumeCode')" @blur="onBlurInput('consumeCode')" />
			</view>
			<view class="btn-box">
				<view class="btn enabled" @click="scanQrCode">
					<image class="icon" src="../../static/scan.png"></image>
					扫码核销
				</view>
			</view>
			<view class="btn-box">
				<view :class="{ btn: true, enabled: isUseButtonEnabled }" @click="useConsumeCodeAsync">核销</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		watch
	} from 'vue';
	
	import {
		useVoucher
	} from '@/api/benefactor-api.js';
	
	import UQRCode from '@/uni_modules/uv-qrcode/components/uv-qrcode/qrcode';

	const phoneNumber = ref('');
	const issuedBenefitsCardNo = ref('');
	const consumeCode = ref('');
	let merchantId = '';
	const productId = ref('');
	const isUseButtonEnabled = ref(false);
	const pslIdentifier = 'psl';
	let voucherId = '';

	// 在页面加载时从本地存储中读取 merchant_id
	onMounted(() => {
		const merchantInfo = uni.getStorageSync('merchantInfo');
		console.log(merchantInfo)
		if (merchantInfo && merchantInfo.merchantId) {
			merchantId = merchantInfo.merchantId;
		} else {
			uni.redirectTo({
				url: `/pages/login/login`
			});
		}
		// 检查登录有效期
		checkExpiration(merchantInfo);
	});

	// 检查登录有效期
	const checkExpiration = (merchantInfo) => {
		if (merchantInfo.expirationDate) {
			const expirationDate = new Date(merchantInfo.expirationDate);
			const currentDate = new Date();

			if (currentDate > expirationDate) {
				console.log('已过有效期');
				uni.redirectTo({
					url: `/pages/login/login`
				});
			} else {
				console.log('未过有效期');
			}
		}
	};

	// 手机号码验证函数
	const isPhoneNumberValid = (phone) => {
		const regex = /^1[3-9]\d{9}$/;
		return regex.test(phone);
	};

	// 核销码验证函数
	const isVerificationCodeValid = (code) => {
		const regex = /^[A-Z]{2}[A-Za-z0-9]{4}$/;
		return regex.test(code);
	};

	// 权益卡号验证函数
	const isIssuedBenefitsCardNoValid = (cardId) => {
		const regex = /^\d{6,}$/;
		return regex.test(cardId);
	};

	// 产品id验证
	const isProductIdValid = (productId) => {
		return productId !== '';
	};

	// 验证输入框并更新按钮状态
	const validateInputs = (inputType) => {
		switch (inputType) {
			case 'phoneNumber':
				if (!isPhoneNumberValid(phoneNumber.value)) {
					uni.showToast({
						title: '请输入正确的手机号码',
						icon: 'none'
					});
				}
				break;
			case 'issuedBenefitsCardNo':
				if (!isIssuedBenefitsCardNoValid(issuedBenefitsCardNo.value)) {
					uni.showToast({
						title: '权益卡号，至少6位数字',
						icon: 'none'
					});
				}
				break;
			case 'consumeCode':
				if (!isVerificationCodeValid(consumeCode.value)) {
					uni.showToast({
						title: '请输入正确的核销码',
						icon: 'none'
					});
				}
			case 'productId':
				if (!isProductIdValid(productId.value)) {
					uni.showToast({
						title: '产品ID不能为空',
						icon: 'none'
					});
				}
				break;
			default:
				isUseButtonEnabled.value =
					isPhoneNumberValid(phoneNumber.value) &&
					isIssuedBenefitsCardNoValid(issuedBenefitsCardNo.value) &&
					isVerificationCodeValid(consumeCode.value) &&
					isProductIdValid(productId.value);
		}
	};

	// 输入框聚焦事件
	const onFocusInput = (inputType) => {
		// validateInputs(inputType);
	};

	// 输入框失去焦点事件
	const onBlurInput = (inputType) => {
		validateInputs(inputType);
	};

	const useConsumeCodeAsync = async () => {
		if (!isUseButtonEnabled.value) {
			return;
		}
		
		uni.showLoading({
			title: "正在核销..."
		});
		try {
			console.log("Using voucher " + voucherId + "...");
			const useVoucherResponse = await useVoucher(voucherId,
				merchantId,
				productId.value,
				phoneNumber.value,
				issuedBenefitsCardNo.value,
				consumeCode.value
			);
			console.log("Successfully used voucher " + voucherId);
			consumeCode.value = '';
			uni.showToast({
				title: '核销成功',
				duration: 2000
			});
		} catch (error) {
			uni.showToast({
				title: error.user_message || '核销失败',
				icon: 'none'
			});
			console.error('Error during verification:', error.message);
		} finally {
			uni.hideLoading();
		}
	};

	const scanQrCode = () => {
		uni.scanCode({
			success: (res) => {
				if (res.result) {
					const scanResult = res.result;
					console.log("The scan result is " + scanResult);
					const parts = scanResult.split(':');
					console.log("The identifier from QR code is " + parts[0]);
					const identifierFromQrCode = parts[0];
					if (identifierFromQrCode !== pslIdentifier) {
						uni.showToast({
							title: '无效的消费码',
							duration: 2000
						});
						return;
					}
					phoneNumber.value = parts[1];
					issuedBenefitsCardNo.value = parts[2];
					productId.value = parts[3];
					consumeCode.value = parts[4];
					voucherId = parts[5];
					validateInputs('');
					useConsumeCodeAsync();
				}
			},
			fail: (err) => {
				console.error('扫描失败:', err);
				uni.showToast({
					title: '扫描失败，请重试',
					icon: 'none',
					duration: 2000
				});
			}
		});
	};
	// 监听变量变化
	watch([phoneNumber, issuedBenefitsCardNo, consumeCode], (newValues, oldValues) => {
		validateInputs('');
	}, {
		deep: true
	});
</script>

<style lang="scss" scoped>
	.content {
		position: relative;
		width: 100%;
		height: 100%;
	}

	.form-box {
		position: fixed;
		z-index: 1;
		background: inherit;
		left: 50rpx;
		right: 50rpx;
		margin-top: 24rpx;
		padding: 60rpx 60rpx 0rpx 60rpx;
		border-radius: 30rpx;
		background-color: #9faa9f;

		.title {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100rpx;
			letter-spacing: 6rpx;
			font-size: 60rpx;
			color: #FFFFFF;
			font-weight: bold;
		}

		.row-input {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin: 40rpx 0rpx;
			height: 100rpx;
			font-size: 28rpx;
			padding: 0 20rpx;
			background-color: #FFFFFF;
			border-radius: 10rpx;
		}

		.btn-box {
			padding: 20rpx 0rpx 38rpx 0rpx;

			.btn {
				display: flex;
				justify-content: center;
				align-items: center;
				width: 100%;
				height: 100rpx;
				border-radius: 10rpx;
				font-size: 35rpx;
				letter-spacing: 5rpx;
				color: #FFFFFF;
				background-color: #808080;
			}

			.enabled {
				color: #FFFFFF;
				background-color: #333333;
			}

			.icon {
				width: 50rpx;
				height: 50rpx;
				margin-right: 24rpx;
			}
		}
	}

	.scan-button {
		position: absolute;
		z-index: 2;
		top: 110rpx;
		right: 20rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100rpx;
		height: 100rpx;
		background-color: #333333;
		border-radius: 50%;
		color: #FFFFFF;
		font-size: 30rpx;
		cursor: pointer;
	}

	/* 在全局样式文件中添加自定义样式 */
	.uni-toast__message {
		white-space: normal !important;
		/* 允许换行 */
		word-wrap: break-word !important;
		/* 允许换行 */
		max-width: none !important;
		/* 取消最大宽度限制 */
	}
</style>